<template>
	<a-card :bordered="false">
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="showTrainModal">
						<template #icon><plus-outlined /></template>
						添加训练数据
					</a-button>
					<xn-batch-button
						buttonName="批量删除"
						icon="DeleteOutlined"
						:selectedRowKeys="selectedRowKeys"
						@batchCallBack="handleBatchDelete"
					/>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'content'">
					<a-tooltip :title="record.content">
						<span>{{ truncateText(record.content, 50) }}</span>
					</a-tooltip>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a-popconfirm title="确定要删除吗？" @confirm="handleDelete(record)">
							<a-button type="link" danger size="small">删除</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>

		<!-- 训练数据对话框 -->
		<a-modal
			v-model:visible="trainModalVisible"
			title="添加训练数据"
			@ok="handleTrainSubmit"
			:confirmLoading="trainLoading"
		>
			<a-form :model="trainForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
				<a-form-item label="数据源" required>
					<a-select v-model:value="trainForm.datasourceId" placeholder="请选择数据源">
						<a-select-option v-for="source in datasourceList" :key="source.id" :value="source.id">
							{{ source.name }}
						</a-select-option>
					</a-select>
				</a-form-item>
			</a-form>
		</a-modal>
	</a-card>
</template>

<script setup name="vectordata">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { listDatabaseSchema, embedDatabaseSchema, deleteVectors } from '@/api/ai/vectordata.js'
import aiDatasourceConfigApi from '@/api/ai/aiDatasourceConfigApi'
import { PlusOutlined } from '@ant-design/icons-vue'

// 表格配置
const tableRef = ref()
const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }

// 定义表格列
const columns = [
	{
		title: '训练类型',
		dataIndex: 'train_type'
	},
	{
		title: '内容',
		dataIndex: 'content'
	},
	{
		title: '数据源名称',
		dataIndex: 'datasourceName'
	},
	{
		title: '数据库',
		dataIndex: 'database'
	},
	{
		title: '表名',
		dataIndex: 'table'
	},
	{
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: 100
	}
]

// 选中行配置
const selectedRowKeys = ref([])
const options = {
	alert: {
		show: true,
		clear: () => {
			selectedRowKeys.value = []
		}
	},
	rowSelection: {
		onChange: (selectedRowKey) => {
			selectedRowKeys.value = selectedRowKey
		}
	}
}

// 加载表格数据
const loadData = async () => {
	try {
		const response = await listDatabaseSchema()
		return {
			records: response,
			total: response.length
		}
	} catch (error) {
		message.error('获取向量库数据失败：' + error.message)
		return {
			records: [],
			total: 0
		}
	}
}

// 训练数据相关
const trainModalVisible = ref(false)
const trainLoading = ref(false)
const trainForm = ref({
	datasourceId: undefined
})
const datasourceList = ref([])

// 显示训练对话框
const showTrainModal = async () => {
	trainModalVisible.value = true
	try {
		const response = await aiDatasourceConfigApi.aiDatasourceConfigPage()
		datasourceList.value = response.records
	} catch (error) {
		message.error('获取数据源列表失败：' + error.message)
	}
}

// 提交训练
const handleTrainSubmit = async () => {
	if (!trainForm.value.datasourceId) {
		message.warning('请选择数据源')
		return
	}

	trainLoading.value = true
	try {
		await embedDatabaseSchema({
			datasourceId: trainForm.value.datasourceId
		})
		message.success('训练数据提交成功')
		trainModalVisible.value = false
		tableRef.value.refresh(true)
	} catch (error) {
		message.error('训练数据提交失败：' + error.message)
	} finally {
		trainLoading.value = false
	}
}

// 删除单条数据
const handleDelete = async (record) => {
	try {
		await deleteVectors([record.id])
		message.success('删除成功')
		tableRef.value.refresh(true)
	} catch (error) {
		message.error('删除失败：' + error.message)
	}
}

// 批量删除
const handleBatchDelete = async (params) => {
	try {
		await deleteVectors(params.map(item => item.id))
		message.success('批量删除成功')
		tableRef.value.clearRefreshSelected()
	} catch (error) {
		message.error('批量删除失败：' + error.message)
	}
}

// 截断文本
const truncateText = (text, length) => {
	if (text.length <= length) return text
	return text.substring(0, length) + '...'
}
</script>
